import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Tree, Button, Select , Icon, Feedback, Loading} from "@icedesign/base";
import axios from 'axios';
import {hashHistory} from 'react-router';
import './RoleManage.scss';
import AddRolesDialog  from '../AddRolesDialog';
import ConfirmDeleteDialog from '../../../Dialog/components/ConfirmDeleteDialog';
import Config from '../../../../utils/Config';
import {GET,POST,PUT} from '../../../../utils/public'

const { Node: TreeNode } = Tree;
export default class RoleManage extends Component {
  static displayName = 'RoleManage';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      treeData:[],
      keyData:[],
      expandedKeys: [],
      selectSource:[],
      autoExpandParent: true, 
      visible: false,       
    };
     this.onChange = this.onChange.bind(this);  
     this.getTreeData = this.getTreeData.bind(this);
     this.handleChildChange=this.handleChildChange.bind(this);//监听子组件变化
  }

  handleChildChange(status){ //处理子函数传回来的status,status为true，执行getTreeData，重新渲染树
    if(status){
      this.getTreeData();
    }
  }
  

  // ICE: React Component 的生命周期

  componentWillMount() {}

  componentDidMount() {
    this.getTreeData();

  }

  componentWillUnmount() {

  }

  getTreeData=()=>{
    //加载loading
    this.setState({'visible':true})
    //取treeData
    const matchedKeys = []; //取出所有节点key值
    const loopKeys = data =>
    data.forEach(item => {
      if (item.id) {
        matchedKeys.push(item.id+','+item.data.id);
      }
      if (item.children && item.children.length) {
        loopKeys(item.children);
      }
    });
    
    const orgnList = [];//取出机构节点 
    const loopOrgnList = data =>
    data.forEach(item => {
      let codeID = item.id+','+item.data.id;
      orgnList.push({label:item.text,value:codeID})
    })
    //请求角色接口，返回角色树
    let url = 'api/permissions/tree';
    const arr = [];
    GET(url)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
          return;
        }else if(res.code == 200 && res.success){
          this.setState({'visible':false})
          this.setState({treeData:res.data});
          loopKeys(res.data);
          loopOrgnList(res.data[0].children);
          orgnList.unshift({label:'全部机构',value:"all"})  //头部追加根节点 
          this.setState({
            expandedKeys: matchedKeys,      //角色树要展开的节点的key数组
            selectSource:orgnList,          //机构数据源
            autoExpandParent: true          //自动展开父节点
          });
        }else if(res.code==401 && res.msg=='请登录!'){
          Feedback.toast.error('等过过期，请重新登录！')
          setTimeout(()=>{
            hashHistory.push('/login');
          },3000) 
        }else{
          Feedback.toast.error(`网络错误，${res.msg}`)
          return;
        }
      },error=>{
        Feedback.toast.error(`网络错误，${error}`)
        return;
      }).catch(errors=>{
        Feedback.toast.error(`出错了，${errors}`)
        return;
      })
  }

  handleCheck=(keys, info)=>{
    //点击节点
    this.setState({
      checkedKeys: keys
    });
  }
  handleExpand=(keys)=> {
    this.setState({
      expandedKeys: keys,
      autoExpandParent: false
    });
  }

  onOpen=(codeID,type)=>{ 
      //调用子页面onOpen方法，打开窗口
      //codeID：当前节点的codeID(id+","+data.id),type: 添加角色类型 add
      this.refs.getOpenButton.onOpen(codeID,type);

  }
  onRightClick=(info)=> {
    let codeID = info.node.props.eventKey;
    let type = 'edit' 
    //调用子页面onOpen方法，打开窗口
    //code：当前节点的code,type: 编辑角色类型 edit
    this.refs.getOpenButton.onOpen(codeID,type);
  }
  
  onEditClick=(codeID,type)=>{
    //调用子页面onOpen方法，打开窗口
    //code：当前节点的code,type: 编辑角色类型 edit
    console.log(codeID,type)
    this.refs.getOpenButton.onOpen(codeID,type);
  }

  onDelete=(id)=>{
    //删除角色
    //id:当前节点 id（即data.id）
    let url = '/api/permissions/'
    this.refs.getDeleteButton.onOpen({id},url);
  }

  onDblClick=()=>{
  }

  onChange=(e)=>{
    //此处拿不到this.state.treeData 重新请求接口
    GET('api/permissions/tree')
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
          return;
        }else if(res.code == 200 && res.success){
          if(e!=='all'){
            //过滤机构重新渲染树
            let code= e.split(',')[0]; //取出节点的code
            //console.log(res.children)
            let index = res.data[0].children.findIndex(item =>item.id === code)
            res.data[0].children =  res.data[0].children.splice(index,1)
          }
          this.setState({treeData:res.data});
        }else if(res.code==401 && res.msg=='请登录!'){
          Feedback.toast.error('等过过期，请重新登录！')
          setTimeout(()=>{
            hashHistory.push('/login');
          },3000) 
        }else{
          Feedback.toast.error(`网络错误，${res.msg}`)
          return;
        }
    },error=>{
      Feedback.toast.error(`网络错误，${error}`)
      return;
    }).catch(errors=>{
      Feedback.toast.error(`出错了，${errors}`)
      return;
    })
  };


  render() {    
    const matchedKeys = [];
    const loop = value =>
    value.map(item => {
      matchedKeys.push(item.id);
      let codeID = item.id+','+item.data.id//codeID格式： code+"code"+parentCode+"code"+id
      //let parentCode = item.data.parentCode
      if(item.text == '权限系统'){
        //根节点
        return (
          <TreeNode label={<div style={styles.divContainer}><div style={styles.divBlock} > <p style={styles.pStyle} onDoubleClick={this.onEditClick.bind(this,codeID,'edit')}>{item.text} </p></div><span style={styles.operBtn}  onClick={this.onOpen.bind(this,codeID,'add')} ><Icon type="add" size="small" /></span></div>} key={codeID}  disabled={item.disabled}> 
            {item.children && item.children.length ? loop(item.children) : null}
          </TreeNode>
       )
      }
      else if(!item.disabled){
        //节点未禁用
        return (
          <TreeNode label={<div style={styles.divContainer}><div style={styles.divBlock} > <p style={styles.pStyle} onDoubleClick={this.onEditClick.bind(this,codeID,'edit')}>{item.text} </p> <span style={styles.operBtn}  onClick={this.onEditClick.bind(this,codeID,'edit')} ><Icon type="edit" size="small" /></span> <span  style={styles.operBtn} onClick={this.onDelete.bind(this,item.data.id)}><Icon type="ashbin" size="small" /></span></div><span style={styles.operBtn}  onClick={this.onOpen.bind(this,codeID,'add')} ><Icon type="add" size="medium" /></span></div>} key={codeID}  disabled={item.disabled}> 
            {item.children && item.children.length ? loop(item.children) : null}
          </TreeNode>
       )
      }else{
        //禁用节点，取消添加
        return (
          <TreeNode label={item.text} key={codeID} onDblClick={this.onDblClick}  disabled={item.disabled}> 
            {item.children && item.children.length ? loop(item.children) : null}
          </TreeNode>
       )
      }
     
    }) 
   
    return (
        <IceContainer>
           <div style={styles.divStyle}>
              <Select   
                style={styles.selectStyle}
                dataSource={ this.state.selectSource} 
                defaultValue="all"
                onChange={this.onChange}
                ></Select>
            </div>
            <Loading visible={this.state.visible} shape="fusion-reactor">
            
            <Tree
              multiple
              showLine
              className="role-tree"
              onRightClick={this.onRightClick.bind(this)}
              expandedKeys={this.state.expandedKeys}
              autoExpandParent={this.state.autoExpandParent}
              onExpand={this.handleExpand.bind(this)}
            >
            {loop(this.state.treeData)}
            </Tree>
            <AddRolesDialog ref="getOpenButton" onGetTree={this.handleChildChange}/>
            <ConfirmDeleteDialog  ref="getDeleteButton" onChange={this.handleChildChange}/>
          </Loading>
        </IceContainer>
     
    );
  }
}
const styles = {
  selectStyle:{ float:'right'},
  buttonStyle:{ borderRadius:"50%"},
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    // background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  pStyle:{
    margin:"3px",
    textAlign:"center",
  },
  divBlock:{
    border:"1px solid #f6f6f6",
    padding: "2px 10px",
    // width:"80px",
    display:"inline-block"
  },
  divContainer:{
    // width:"120px",
    vertical:"middle"
  },
  divStyle:{
    display:"block"
  }
};

